﻿using System;
using Colorful.Furniture.PermissionManagement;
using Colorful.Furniture.Wrappers;
using FreeSql;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;
using Colorful.Furniture.Extensions;
using Volo.Abp.Application.Services;
using Volo.Abp.Auditing;

namespace Colorful.Furniture.SysManagement
{
    /// <summary>
    ///  审计日志服务
    /// </summary>
    [DisableAuditing]
    public class ApiLogAppService : ApplicationService
    {
        private readonly IBaseRepository<SysApiLog> _logRepository;
        private readonly IFreeSql _freeSql;

        public ApiLogAppService(
            IBaseRepository<SysApiLog> logRepository,
            IFreeSql freeSql)
        {
            _logRepository = logRepository;
            _freeSql = freeSql;
        }

        /// <summary>
        ///  日志分页
        /// </summary>
        /// <param name="input">分页请求</param>
        /// <returns></returns>
        public async Task<PageResponseWrapper<List<LogPageOutputDto>>> PostPagedAsync([FromBody] LogPageInputDto input)
        {
            //请求结果
            var requestResult = input.OperationResult == 0;

            int? addStartDate = input.OperationDate?.Count == 2 ? Convert.ToDateTime(input.OperationDate[0]).ToString("yyyyMMdd").ToInt() : null;
            int? addEndDate = input.OperationDate?.Count == 2 ? Convert.ToDateTime(input.OperationDate[1]).ToString("yyyyMMdd").ToInt() : null;

            var pageOutputList = await _freeSql.Select<SysApiLog, SysManager>()
                .LeftJoin(x=>x.t1.OperatorId == x.t2.Id)
                .WhereIf(input.AuthorizationType.HasValue, x => x.t1.AuthorizationType == input.AuthorizationType)
                .WhereIf(!string.IsNullOrWhiteSpace(input.Browser), x => x.t1.Browser.Contains(input.Browser))
                .WhereIf(!string.IsNullOrWhiteSpace(input.Keywords), x => x.t1.Operator.Contains(input.Keywords) || x.t1.RequestInput.Contains(input.Keywords) || x.t1.Remark.Contains(input.Keywords) || (x.t1.ActionDescription + x.t1.Action).Contains(input.Keywords) || x.t1.RequestUrl.Contains(input.Keywords))
                .WhereIf(!string.IsNullOrWhiteSpace(input.Ip), x => x.t1.Ip.Contains(input.Ip))
                .WhereIf(!string.IsNullOrWhiteSpace(input.ActionDescription), x => x.t1.RequestUrl.Contains(input.ActionDescription))
                .WhereIf(input.OperationResult.HasValue, x => x.t1.Success == requestResult)
                .WhereIf(addStartDate.HasValue && addEndDate.HasValue, (x) => Convert.ToInt32(Convert.ToDateTime(x.t1.AddTime).ToString("yyyyMMdd")) >= addStartDate &&
                                                                              Convert.ToInt32(Convert.ToDateTime(x.t1.AddTime).ToString("yyyyMMdd")) <= addEndDate)
                .Count(out var pageTotalCount)
                .Page(input.PageIndex, input.PageSize)
                .OrderByDescending(x => x.t1.AddTime)
                .ToListAsync(x => new LogPageOutputDto
                {
                    ActionDescription = x.t1.RequestUrl.Replace("/api/app", ""),
                    OperatorName = x.t2.Name
                });

            return new PageResponseWrapper<List<LogPageOutputDto>>
            {
                Total = pageTotalCount,
                Items = pageOutputList
            };
        }

        /// <summary>
        ///  获取详情
        /// </summary>
        /// <returns></returns>
        public async Task<LogInfoOutputDto> GetDetailAsync(Guid id)
        {
            var model = await _freeSql.Select<SysApiLog, SysManager>()
                .LeftJoin(x => x.t1.OperatorId == x.t2.Id)
                .Where(x => x.t1.Id == id)
                .ToOneAsync(x => new LogInfoOutputDto
                {
                    OperatorName = x.t2.Name
                });

            return model;
        }
    }
}